package com.holly.common_view;

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.holly.common.utils.L;

import java.util.ArrayList;
import java.util.List;

/**
 * 每个Item高度固定，居中
 * 2016/12/6 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
public class AutoWrapLayout extends FrameLayout {
    protected final String TAG = L.createTag(this);
    private static final int DEFAULT_Item_WIDTH = 300;
    private static final int DEFAULT_Item_HEIGHT = 30;
    private static final int DEFAULT_ITEM_PADDING = 5;

    private int mItemHeight;
    private int mItemPaddingLeft;
    private int mItemPaddingRight;
    private int mItemPaddingTop;
    private int mItemPaddingBottom;

    //折叠状态
    private ViewGroup.LayoutParams mItemParams;

    //adapter
    protected BaseAutoWrapAdapter mAdapter;

    //缓存类型的View--不包含已经添加进去的
    protected List<View> mViewCacheList = new ArrayList<View>();
    //当前包含的Child
    protected List<View> mChildViewList = new ArrayList<View>();
    //adapter是否发生改变
    protected boolean mIsAdapterChanged = false;

    public AutoWrapLayout(Context context) {
        super(context);
        init();
    }

    public AutoWrapLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AutoWrapLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    protected void init() {
        mItemHeight = DEFAULT_Item_HEIGHT;
        mItemPaddingTop = DEFAULT_ITEM_PADDING;
        mItemPaddingBottom = DEFAULT_ITEM_PADDING;
        mItemPaddingLeft = DEFAULT_ITEM_PADDING;
        mItemPaddingRight = DEFAULT_ITEM_PADDING;
        mItemParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMeasure = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMeasure = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
            widthMeasure = DEFAULT_Item_WIDTH;
        }

        //开始计算行数
        int lines = 0;
        int width = 0;
        int childCount = getChildCount();
        int tempWidth = widthMeasure - getPaddingLeft() - getPaddingRight();
        int horizontalPadding = mItemPaddingLeft + mItemPaddingRight;
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                //子类满足最大宽度
                child.measure(MeasureSpec.makeMeasureSpec(tempWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(mItemHeight, MeasureSpec.EXACTLY));
                if (child.getMeasuredWidth() > tempWidth - horizontalPadding) {
                    child.setMinimumWidth(tempWidth - horizontalPadding);
                }

                width += child.getMeasuredWidth() + horizontalPadding;
                if (width > tempWidth) {
                    width = child.getMeasuredWidth() + horizontalPadding;
                    lines++;
                }
            }
        }
        int totalRows = lines + 1;
        int verticalPadding = mItemPaddingTop + mItemPaddingBottom;
        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            heightMeasure = getPaddingTop() + getPaddingBottom() + (verticalPadding + mItemHeight) * totalRows;
        }
        setMeasuredDimension(widthMeasure, heightMeasure);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int childCount = getChildCount();
        int maxWidth = r - l - getPaddingLeft() - getPaddingRight();
        int endX = 0;
        int endY = 0;
        int horizontalPadding = mItemPaddingLeft + mItemPaddingRight;
        int verticalPadding = mItemPaddingLeft + mItemPaddingRight;
        for (int i = 0; i < childCount; i++) {
            final View child = this.getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                int width = child.getMeasuredWidth();
                int height = child.getMeasuredHeight();

                endX = endX + child.getMeasuredWidth() + horizontalPadding;
                if (endX >= maxWidth) {
                    endX = child.getMeasuredWidth() + horizontalPadding;
                    endY = endY + height + verticalPadding;
                } else if (endY == 0) {
                    endY = height + verticalPadding;
                }
//                int x1 = endX + getPaddingLeft() - width;
//                int x2 = endX + getPaddingLeft() - mItemPaddingRight;
//                int y1 = endY + getPaddingTop() - height - mItemPaddingBottom;
//                int y2 = endY + getPaddingTop() - mItemPaddingBottom;
                child.layout(endX + getPaddingLeft() - width - mItemPaddingRight, endY + getPaddingTop() - height - mItemPaddingBottom, endX + getPaddingLeft() - mItemPaddingRight, endY + getPaddingTop() - mItemPaddingBottom);
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    //设置Item间隔
    public void setItemPadding(int left, int top, int right, int bottom) {
        if (left < 0 || top < 0 || right < 0 || bottom < 0) {
            throw new IllegalArgumentException("left、top、right 、bottom padding不能小于0");
        }
        mItemPaddingLeft = left;
        mItemPaddingTop = top;
        mItemPaddingRight = right;
        mItemPaddingBottom = bottom;
        requestLayout();
    }

    //刷新页面
    public void notifyDataChanged() {
        if (mAdapter == null) {
            removeAllViews();
            return;
        }
        mAdapter.setAutoWrapLayout(this);

        if (mIsAdapterChanged) {
            removeAllViews();
        }

        List<View> viewPollList = new ArrayList<>();
        viewPollList.addAll(mChildViewList);
        viewPollList.addAll(mViewCacheList);
        int count = mAdapter.getItemCount();
        int poolViewCount = viewPollList.size();
        int maxCount = count > poolViewCount ? count : poolViewCount;
        for (int i = 0; i < maxCount; i++) {
            if (i < count) {
                View view;
                if (i < poolViewCount) {
                    view = viewPollList.get(i);
                } else {
                    view = mAdapter.getView(getContext());
                }
                addItemView(view);
                mAdapter.bindView(this, view, i);
            } else {
                //表示原来的View太多
                View view = viewPollList.get(i);
                removeItemView(view);
            }
        }
        requestLayout();
    }

    //移除View
    protected void removeItemView(View child) {
        if (mChildViewList.contains(child)) {
            mChildViewList.remove(child);
            mViewCacheList.add(child);
            removeView(child);
        }
    }

    //添加View
    protected void addItemView(View child) {
        if (!mChildViewList.contains(child)) {
            mChildViewList.add(child);
            mViewCacheList.remove(child);
            addView(child, mItemParams);
        }
    }

    //移除所有的Views
    protected void removeAllItemViews() {
        if (!mIsAdapterChanged) {
            mViewCacheList.addAll(mChildViewList);
        }
        mChildViewList.clear();
        removeAllViews();
    }

    public void setAdapter(BaseAutoWrapAdapter adapter) {
        if (adapter != mAdapter) {
            mIsAdapterChanged = true;
        }
        mAdapter = adapter;
        notifyDataChanged();
        mIsAdapterChanged = false;
    }

    public static abstract class BaseAutoWrapAdapter<Bean> {
        private final String TAG = L.createTag(this);
        AutoWrapLayout mAutoWrapLayout;

        private void setAutoWrapLayout(AutoWrapLayout autoWrapLayout) {
            mAutoWrapLayout = autoWrapLayout;
        }

        //当前界面显示所使用的List
        protected final List<Bean> mList = new ArrayList<Bean>();

        public void setList(@Nullable List<Bean> list) {
            mList.clear();
            if (list != null) {
                mList.addAll(list);
                L.d(TAG, "setList.size = " + mList.size());
            } else {
                L.d(TAG, "setList: size = 0");
            }
        }

        public List<Bean> getList() {
            List list = new ArrayList();
            list.addAll(mList);
            L.d(TAG, "getList.size = " + list.size());
            return list;
        }

        public int getItemCount() {
            return mList.size();
        }

        public abstract View getView(Context context);

        public abstract void bindView(View parent, View itemView, int position);

        public void notifyDataChanged() {
            mAutoWrapLayout.notifyDataChanged();
        }
    }
}
